package com.henryschein.mmvvcc.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.henryschein.mmvvcc.model.Person;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class PersonDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Person find(Long id) {
        return entityManager.find(Person.class, id);
    }

    @SuppressWarnings("unchecked")
    public List<Person> getPeople() {
        return entityManager.createQuery("select p from Person p").getResultList();
    }
    
    @SuppressWarnings("unchecked")
    public List<Person> sotrPeople(String cat) {
        return entityManager.createQuery("select p from Person p where p.category=:arg1").setParameter("arg1", cat).getResultList();
    }

    @Transactional
    public Person save(Person person) {
        if (person.getId() == null) {
            entityManager.persist(person);
            return person;
        } else {
            return entityManager.merge(person);
        }
    }

    @Transactional
    public void remove(Person person) {
        entityManager.remove(entityManager.getReference(Person.class, person.getId()));
    }
}
